#!/usr/bin/perl
#
# Create a GNUPLOT command file from a history file
# Values to plot for are given on the command line
#
# NOTE: This creates 2 tempfiles and runs plot..
#BEGIN { push @INC,"/home/counter/counter/lib/";}
use English;
use Reportsub;
use Getopt::Long;

$usage = "Usage: $0 [-p] [-f date] [--delta] mark... < inputfile\n";

$xsize = 0.8; # default

GetOptions("popscale|p" => \$popscale,
	   "fromdate|f=s" => \$fromdate,
	   "delta|d" => \$delta,
	   "png" => \$png,
	   "size=f" => \$xsize,
	   );

if ($png) {
    $format = "png";
} else {
    $format = "gif";
}
$ysize = $xsize * 0.5/0.8;

@keys = @ARGV;
for $choose (@keys) {
    $doit{$choose} = 1;
}
if ($popscale) {
    getcountryinfo;
    $population{All} = $population{XW};
    $ylabel = "Users/Mpop";
} else {
    $ylabel = "Users";
}

while (<STDIN>) {
    chop;
    if (/:(\S+):/) {
	$date = $`;
	$selector = $1;
	$value = $';
	if (!$doit{$selector}) {
	    next;
	}
	if ($popscale) {
	    if ($population{$selector} == 0) {
		$plot{$selector}{$date} = 1;
	    } else {
		$plot{$selector}{$date} = $value/$population{$selector};
	    }
	} else {
	    $plot{$selector}{$date} = $value;
	}
    }
}
#open(PLOT, "|gnuplot") || die "Unable to open plotfile\n";
open(PLOT, ">-");
print PLOT <<EoF;
# Accept dates as input
set xdata time
set timefmt "%Y-%m-%d"
set xlabel "Year"
set format x "%Y"
set ylabel "$ylabel"
set terminal $format
set size $xsize,$ysize
set xtics ("1992-01-01", "1994-01-01", "1996-01-01", "1998-01-01", "2000-01-01", "2002-01-01", "2004-01-01", "2006-01-01", "2008-01-01", "2010-01-01")
set key top left
EoF

print PLOT "plot ";

for $val (@keys) {
    print PLOT ", " if $notfirst;
    $notfirst = 1;
    print PLOT "'-' using 1:2 title \"$val\" with lines";
}
print PLOT"\n\n";
#close PLOT;

# Plot it out again in squarish fashion
for $selector (@keys) {
    # Fake entry at 0, 1994; this rescales the plots too.
    if (!$fromdate) {
	print PLOT "1994-01-01 0\n";
    }
    $pointcount = 0;
    $donezero = 0;
    $prev = 0;
    for $date (sort(keys(%{$plot{$selector}}))) {
	++ $pointcount;
	if ($donezero eq 0 && !$fromdate) {
	    print PLOT "$date 0\n";
	    $donezero = 1;
	}
	if ($delta) {
	    if ($date ge $fromdate) {
		$diff = $plot{$selector}{$date} - $prev;
		if ($diff > 0) {
		    print PLOT "$date $diff\n";
		} else {
		    print PLOT "$date 0\n";
		    warn "$selector $date - delta $diff, printing 0\n";
		}
	    }
	    $prev = $plot{$selector}{$date};
	} else {
	    print PLOT "$date $plot{$selector}{$date}\n" if $date ge $fromdate;
	}
    }
    print PLOT "end\n";
    if ($pointcount == 0) {
	warn "Plot of $selector: No data points\n";
    }
}
close DATA;
